<?php
// +----------------------------------------------------------------------
// | UCToo [ Universal Convergence Technology ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014-2021 https://www.uctoo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Patrick <contact@uctoo.com>
// +----------------------------------------------------------------------

namespace uctoo\library\traits;

trait Wechatopen
{
    /**
     * 微信接口数据返回
     * @param $data
     * @param bool $error_code_range
     * @param callable $callback
     */
    protected function wxResult($data,$error_code_range = false,callable $callback = null){
        if(0 !== $data['errcode']){
            $code = 0;
            $error_msg = $data['errmsg'];
            if($error_code_range){
                $error_msg = $this->parseWxErrMsg($error_code_range,$data['errcode']);
                if(85088 == $data['errcode']){
                    $code = 102;
                }
            }
            $this->error($error_msg,$data,$code);
        }else{
            unset($data['errcode'],$data['errmsg']);
            is_callable($callback) && call_user_func_array($callback, [&$data]);
            $this->success('ok',null,$data);
        }
    }

    /**
     * @param $error_code_range
     * @param $err_code
     * @return string
     */
    protected function parseWxErrMsg($error_code_range,$err_code){
        $_path = $this->app->getAppPath().'util'.DIRECTORY_SEPARATOR.'WxErrorCode'.DIRECTORY_SEPARATOR.$error_code_range.'.php';
        if(is_file($_path)){
            $lang = include $_path;

        }
        return $lang[$err_code] ?? '';
    }
}
